package com.missfresh.cooperation2meituan.controller;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.missfresh.cooperation2meituan.service.OrderExtendService;
import com.missfresh.cooperation2meituan.util.CommonUtil;
import com.missfresh.cooperation2meituan.util.HttpUtil;
import com.missfresh.cooperation2meituan.util.JsonUtil;
import com.missfresh.cooperation2meituan.util.MD5Util;
import com.missfresh.cooperation2meituan.util.SignUtil;
/**
 * 扩展Controller
 * @author supeng 20151209
 */
@Controller
@RequestMapping("orderExtend")
public class OrderExtendController {
	private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
	
	@Autowired
	private OrderExtendService orderExtendService;
	
	@Value("${DELIVERING_URL}")
	private String DELIVERING_URL;
	@Value("${ARRIVED_URL}")
	private String ARRIVED_URL;
	@Value("${app.id}")
	private String APP_ID;
	@Value("${CONSUMER_SECRET}")
	private String CONSUMER_SECRET;
	
	/**
	 * 订单配送中
	 * @param order_id 订单ID
	 * @param courier_name 配送员姓名
	 * @param courier_phone 配送电话
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/orderDelivering.do", method=RequestMethod.POST)
	public Object  orderDelivering(@RequestParam("order_id") String order_id,
			@RequestParam("courier_name") String courier_name,
			@RequestParam("courier_phone") String courier_phone) {
		System.out.println(courier_name);
		logger.info("Enter orderDelivering(订单配送中) Method!");
		String returnStr="";
		StringBuffer sb=new StringBuffer();
		String timestamp=System.currentTimeMillis()+"";
		sb.append("app_id="+APP_ID);
		sb.append("&courier_name="+courier_name);
		sb.append("&courier_phone="+courier_phone);
		sb.append("&order_id="+order_id);
//		sb.append("&courier_name="+courier_name);
//		sb.append("&courier_phone="+courier_phone);
		sb.append("&timestamp="+timestamp); //时间戳
//		String sig=MD5Util.MD5(DELIVERING_URL_TEST+"?"+APP_ID+"&"+sb.toString()+CONSUMER_SECRET);
		List<String> list=new ArrayList<String>();
		list.add("app_id="+APP_ID);
		list.add("order_id="+order_id);
		list.add("courier_name="+courier_name);
		list.add("courier_phone="+courier_phone);
		list.add("timestamp="+timestamp);
		String sig=SignUtil.createSign(list, DELIVERING_URL);
		/**
		 * 调订单系统接口Get请求
		 * TODO data返回中文乱码
		 */
		String data=HttpUtil.sendGet(DELIVERING_URL, sb.toString()+"&sig="+sig);
		logger.info("调用订单配送中，美团返回数据："+data);
		try {
			Map<String,Object> returnMap=JsonUtil.json2map(data);
			if("ok".equals(returnMap.get("data"))){
				returnStr="{\"data\": \"ok\"}";
			}else{
				returnStr="{\"data\": \"error\"}";
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			returnStr="{\"data\": \""+e.getMessage()+"\"}";
		}
		logger.info("返回："+returnStr);
		return returnStr;
	}
	/**
	 * 订单已送达
	 * @param order_id 订单ID
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/orderArrived.do", method=RequestMethod.POST)
	public Object  orderArrived(@RequestParam("order_id") String order_id) {
		logger.info("Enter orderArrived(订单已送达) Method!");
		String returnStr="";
		String timestamp=System.currentTimeMillis()+"";
		StringBuffer sb=new StringBuffer();
		sb.append("app_id="+APP_ID);
		sb.append("&order_id="+order_id);
		sb.append("&timestamp="+System.currentTimeMillis());
		/**
		 * URL：
		 * ARRIVED_URL_TEST  测试环境
		 * Constant.ARRIVED_URL  线上环境
		 */
//		String sig=MD5Util.MD5(ARRIVED_URL_TEST+"?"+APP_ID+"&"+sb.toString()+CONSUMER_SECRET);
		List<String> list=new ArrayList<String>();
		list.add("app_id="+APP_ID);
		list.add("order_id="+order_id);
		list.add("timestamp="+timestamp);
		String sig=SignUtil.createSign(list, ARRIVED_URL);
		/**
		 * TODO data返回中文乱码
		 */
		String data=HttpUtil.sendGet(ARRIVED_URL, sb.toString()+"&sig="+sig);
		try {
			Map<String,Object> returnMap=JsonUtil.json2map(data);
			if("ok".equals(returnMap.get("data"))){
				returnStr="{\"data\": \"ok\"}";
			}else{
				returnStr="{\"data\": \"error\"}";
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			returnStr="{\"data\": \""+e.getMessage()+"\"}";
		}
		logger.info("返回："+returnStr);
		return returnStr;
	}
	/**
	 * 更新物流配送状态
	 * @param params
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/logisticsInfo.do", method=RequestMethod.POST)
	public Object  orderDelivery(@RequestParam Map<String,Object> params) {
		logger.info("Enter logisticsInfo(更新物流配送状态) Method!");
		String returnStr="";
		String order_id=params.containsKey("order_id")?(String)params.get("order_id"):null;
		String courier_name=params.containsKey("courier_name")?(String)params.get("courier_name"):null;
		String courier_phone=params.containsKey("courier_phone")?(String)params.get("courier_phone"):null;
		String delivery_time=params.containsKey("delivery_time")?(String)params.get("delivery_time"):null;
		String delivery_status=params.containsKey("delivery_status")?(String)params.get("delivery_status"):null;
		/**
		 * 物流无法区分订单是哪种渠道，去掉此参数
		 */
//		String channel=params.containsKey("channel")?(String)params.get("channel"):null;
//		if("meituan".equals(channel)){
			if(delivery_status==null||"".equals(delivery_status)){
				returnStr="{\"data\": \"参数错误\"}";
				logger.info("返回结果：参数错误");
			}
			StringBuffer sb=new StringBuffer();
			List<String> list=new ArrayList<String>();
			String timestamp=System.currentTimeMillis()+"";
			sb.append("app_id="+APP_ID);
			list.add("app_id="+APP_ID);
			if(order_id==null||"".equals(order_id)){
				returnStr="{\"data\": \"参数错误，order_id为空\"}";
				logger.info("返回结果：参数错误，order_id为空");
			}else{
				sb.append("&order_id="+order_id);
				list.add("order_id="+order_id);
			}
			sb.append("&timestamp="+timestamp); //时间戳
			list.add("timestamp="+timestamp);
			//订单配送中
			if("0".equals(delivery_status)){
				if(courier_name!=null&&!"".equals(courier_name)&&courier_phone!=null&&!"".equals(courier_phone)){
					sb.append("&courier_name="+courier_name);
					sb.append("&courier_phone="+courier_phone);
					list.add("courier_name="+courier_name);
					list.add("courier_phone="+courier_phone);
				}else{
					returnStr="{\"data\": \"配送人员信息有误\"}";
					logger.info("返回结果：配送人员信息有误");
				}
				String sig=SignUtil.createSign(list, DELIVERING_URL);
				returnStr=meituanDelivery(DELIVERING_URL, sb.toString()+"&sig="+sig);
			//订单已送达
			}else if("1".equals(delivery_status)){
				String sig=SignUtil.createSign(list, ARRIVED_URL);
				returnStr=meituanDelivery(ARRIVED_URL, sb.toString()+"&sig="+sig);
			}
//		}else if("baidu".equals(channel)){
//			
//		}else if("elema".equals(channel)){
//			
//		}
		return returnStr;
	}
	/**
	 * 更新美团配送状态
	 * @param url
	 * @param params
	 * @return
	 */
	public String meituanDelivery(String url,String params){
		String returnStr="";
		String data=HttpUtil.sendGet(url, params);
		logger.info("调用订单配送中，美团返回数据："+data);
		try {
			Map<String,Object> returnMap=JsonUtil.json2map(data);
			if("ok".equals(returnMap.get("data"))){
				returnStr="{\"data\": \"ok\"}";
			}else{
				returnStr="{\"data\": \"error\"}";
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			returnStr="{\"data\": \""+e.getMessage()+"\"}";
		}
		logger.info("返回结果："+returnStr);
		return returnStr;
	}
	/**
	 * TODO 用户或客服取消订单
	 * @param order_id 订单ID
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/cancleOrder.do", method=RequestMethod.GET)
	public Object  cancleOrder(@RequestParam("order_id") String order_id) {
		logger.info("Enter cancleOrder(用户或客服取消订单) Method!");
		return "{\"data\": \"ok\"}";
	}
	/**
	 * 测试查询
	 * @param params2
	 */
	@ResponseBody
	@RequestMapping(value="/query.do", method=RequestMethod.GET)
	public void  query(@RequestParam Map<String,Object> params2) {
		Map<String,Object> params=new HashMap<String, Object>();
		String app_poi_code="111";
//		String wma_store_code="222";
//		String tms_store_code="333";
		//111 222 333     1
		//111     333     1
		//111             2
		//222             2
		params.put("app_poi_code", app_poi_code);
//		params.put("wma_store_code", wma_store_code);
//		params.put("tms_store_code", tms_store_code);
//		Map<String,Object> lmtParams=CommonUtil.preparePage(null);
//		params.putAll(lmtParams);
//		List<Map<String,Object>> list=orderExtendService.queryMeituanInventoryAppstore(params);
//		System.out.println(list.size()+"---------------");
//		System.out.println("---------------------------------------------------------------");
//		System.out.println(list);
//		System.out.println("---------------------------------------------------------------");
	
//		List<String> list=orderExtendService.queryAppPoiCode();
//		System.out.println(list+"---------------------list");
		List<Map<String,Object>> listMap=orderExtendService.querySpuAndSkuByParams(params);
		System.out.println(listMap+"----------------------listMap");
	}
	/**
	 * Test
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(System.currentTimeMillis());
		Map<String,Object> params=new HashMap<String, Object>();
		String app_poi_code="111";
		String wma_store_code="222";
		String tms_store_code="333";
		params.put("app_poi_code", app_poi_code);
		params.put("wma_store_code", wma_store_code);
		params.put("tms_store_code", tms_store_code);
		Map<String,Object> lmtParams=CommonUtil.preparePage(null);
		params.putAll(lmtParams);
//		orderExtendService.queryMeituanInventoryAppstore(params);
	}
	//1449721755316
}
